﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Abp;
using Abp.Domain.Repositories;
using Abp.ObjectMapping;
using Abp.Runtime.Caching;
using AutoMapper.QueryableExtensions;
using FwProject.Car.Dto;
using FwProject.Manager;
using X.PagedList;

namespace FwProject.Car
{
    public class CarMapAppService: FwProjectAppServiceBase,ICarMapAppService
    {
        private readonly IRepository<CarMap, Guid> _repositoryCarMap;
        private readonly CarMapManager _carMapManager;
        public readonly ICacheManager _catchmanager;
        public IGuidGenerator _guid { get; set; }
        public IObjectMapper _map { get; set; }

        public CarMapAppService(IRepository<CarMap, Guid> repositoryCarMap, ICacheManager catchmanager, CarMapManager carMapManager)
        {
            _repositoryCarMap = repositoryCarMap;
            _catchmanager = catchmanager;
            _carMapManager = carMapManager;
            _guid = SequentialGuidGenerator.Instance;
        }
     #region app 添加车辆的定位信息信息
        /// <summary>
        /// app 添加车辆的定位信息信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<Guid> Create(CarMapInput input)
        {
            var model = _map.Map<CarMap>(input);
            model.Id = _guid.Create();
            return await _carMapManager.CreateCarMap(model);
        }
        #endregion
        public async Task Update(Guid id,CarMapInput input)
        {
            var model = await _repositoryCarMap.GetAsync(id);
            model = _map.Map(input, model);
            await _carMapManager.UpdateCarMap(model);
        }

        public async Task Delete(Guid id)
        {
            var model = await _repositoryCarMap.GetAsync(id);
            await _carMapManager.DeleteCarMap(model);
        }

        public async Task<CarMapDto> GetByIdAsync(Guid id)
        {
            var model = (await GetCache).Where(o => o.Id == id).FirstOrDefault();
            return _map.Map<CarMapDto>(model);

        }
        /// <summary>
        /// 获取车辆的所有定位列表
        /// </summary>
        /// <param name="pageIdx"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public async Task<IPagedList<CarMapDto>> GetPagedListAsync(int pageIdx, int pageSize)
        {
            var listmodel = (await GetCache).AsQueryable();
            return await listmodel.ProjectTo<CarMapDto>().ToPagedListAsync(pageIdx, pageSize);
        }

        private Task<List<CarMap>> GetCache
        {
            get
            {
                ICache cache = _catchmanager.GetCache(nameof(CarMap));
                return cache.GetAsync($"list", async () => (await _repositoryCarMap.GetAllListAsync()).Where(o=>o.CreationTime>=DateTime.Now.AddDays(-5)).ToList());
            }

        }
    }
}
